<template>
  <div>
    <div v-for="item in fileList" class="mb-10">
      <span class="atag" @click="downloadTheFile(item.url,item.name)">{{ item.name }}</span>
      <span class="atag" style="margin-left:20px;" @click="previewTheFile(item.url,item.name)">{{ canPreview(item.name) }}</span>
    </div>

    <div>
      <viewer  :images="images"
               :options="options"
               @inited="inited"
              class="viewer" ref="viewer"
      >
        <template #default="scope">
          <img v-for="src in scope.images" :src="src" :key="src">

        </template>
      </viewer>
    </div>
  </div>


</template>

<script>
import { downloadTheFile, downloadUrl, previewPdf } from '@/utils'
import 'viewerjs/dist/viewer.css'
import { component as Viewer } from "v-viewer"

export default {
  name: 'DownOrPreview',
  components: {
    Viewer
  },
  props:{
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    const toolbar={
      zoomIn: 4,
      zoomOut: 4,
      oneToOne: 4,
      reset: 4,
      prev: 0,
      play: {
        show: 4,
        size: 'large',
      },
      next: 0,
      rotateLeft: 4,
      rotateRight: 4,
      flipHorizontal: 4,
      flipVertical: 4,
    }
    return {
      dialogTableVisible: false,
      previewImgSrc:'',
      previewImgName:'',
      images:[],

      options: {  "button": true, "navbar": true, "title": true, "toolbar": toolbar, "tooltip": true, "movable": true, "zoomable": true, "rotatable": true, "scalable": true, "transition": true, "fullscreen": true, "keyboard": true}
    }
  },

  methods: {
    downloadTheFile,
    previewTheFile(url, fileName) {
      this.previewImgSrc='';
      this.previewImgName='';
      downloadUrl(url).then(result => {
        let fileNameArray=fileName.split(".");
        let fileType=fileNameArray.pop().toLowerCase();
        if(fileType==='pdf'){
          previewPdf(result,fileName)
        }
        let imgType=['jpg','png','jpeg','gif']
        if(imgType.includes(fileType)){

          let urlCreator = window.URL || window.webkitURL;
          let imageUrl = urlCreator.createObjectURL(result);
          this.previewImgSrc=imageUrl;
          this.images=[this.previewImgSrc]
          this.previewImgName=fileName;
          // this.dialogTableVisible=true;
          this.$viewer.show()
        }

      }).catch((e) => {
        console.log(e)
      })

    },
    canPreview(name) {
      let nameArray=name.split(".");
      let fileType=nameArray.pop().toLowerCase();
      let previewType=['pdf','jpg','png','jpeg','gif']
      if(previewType.includes(fileType)){
        return '预览'
      }else{
        return ''
      }
    },
    inited (viewer) {
      this.$viewer = viewer
    },
  }

}
</script>

<style scoped>
.viewer{
  display:none;
}
</style>
